import { Button, Card, Col, Form, Input, Modal, Popconfirm, Row, Space } from 'antd';
import Table, { ColumnsType } from 'antd/es/table';
import { TableRowSelection } from 'antd/es/table/interface';
import { useEffect } from 'react';

import Editor from '@/components/editor';
import { IconButton, Iconify } from '@/components/icon';
import { useCommon } from '@/hooks/common';
import { useRouter } from '@/router/hooks';

export default function PropertyPage() {
  const uri = 'base-property';
  const cateName = '网站配置';
  const { push } = useRouter();
  const formParams = {
    title: '',
    detail: '',
    id: 0,
  };
  const {
    data = {},
    ModalPros,
    searchForm,
    onSearchFormReset,
    onCreate,
    doDel,
    onSearch,
    handleChange,
  } = useCommon({ title: '' }, uri, {
    ...formParams,
  });

  const toEdit = (params: any) => {
    push(`/operate/property/editor?id=${params.id}`);
  };

  const columns: ColumnsType<any> = [
    { title: '编号', dataIndex: 'id', width: 60 },
    { title: '标题', dataIndex: 'title', width: 100 },
    {
      title: '内容',
      dataIndex: 'detail',
      align: 'center',
      width: 120,
      render: (content) => <div className="truncate">{content.substr(0, 60)}</div>,
    },
    { title: '创建时间', dataIndex: 'createTime', align: 'center', width: 200 },
    { title: '更新时间', dataIndex: 'updateTime', align: 'center', width: 200 },
    {
      title: '操作',
      key: 'operation',
      align: 'center',
      width: 100,
      render: (_, record) => (
        <div className="flex w-full justify-center text-gray">
          <IconButton onClick={() => toEdit(record)}>
            <Iconify icon="solar:pen-bold-duotone" size={18} />
          </IconButton>
          <Popconfirm
            title="确认删除该数据？"
            okText="确定"
            cancelText="取消"
            placement="left"
            onConfirm={() => doDel(record.id)}
          >
            <IconButton>
              <Iconify icon="mingcute:delete-2-fill" size={18} className="text-error" />
            </IconButton>
          </Popconfirm>
        </div>
      ),
    },
  ];

  // rowSelection objects indicates the need for row selection
  const rowSelection: TableRowSelection<any> = {
    onChange: (selectedRowKeys, selectedRows) => {
      console.log(`selectedRowKeys: ${selectedRowKeys}`, 'selectedRows: ', selectedRows);
    },
    onSelect: (record, selected, selectedRows) => {
      console.log(record, selected, selectedRows);
    },
    onSelectAll: (selected, selectedRows, changeRows) => {
      console.log(selected, selectedRows, changeRows);
    },
  };

  return (
    <Space direction="vertical" size="large" className="w-full">
      <Card>
        <Form form={searchForm} onFinish={onSearch}>
          <Row gutter={[16, 16]}>
            <Col span={8} lg={6}>
              <Form.Item<any> label="标题" name="title" className="!mb-0">
                <Input />
              </Form.Item>
            </Col>
            <Col span={24} lg={12}>
              <div className="flex justify-end">
                <Button onClick={onSearchFormReset}>重置</Button>
                <Button type="primary" htmlType="submit" className="ml-4">
                  查询
                </Button>
              </div>
            </Col>
          </Row>
        </Form>
      </Card>

      <Card
        title={cateName}
        extra={
          <div className="flex flex-row gap-[10px]">
            <Button type="primary" onClick={() => onCreate({ ...formParams })}>
              新增
            </Button>
          </div>
        }
      >
        <Table
          rowKey="id"
          size="small"
          pagination={{ total: data.totalCount }}
          scroll={{ x: 'max-content' }}
          columns={columns}
          dataSource={data.list}
          rowSelection={{ ...rowSelection }}
          onChange={handleChange}
        />
      </Card>

      <CommonModal {...ModalPros} />
    </Space>
  );
}

function CommonModal({ title, show, formValue, onOk, onCancel }: any) {
  const [form] = Form.useForm();
  useEffect(() => {
    form.setFieldsValue({ ...formValue });
  }, [formValue, form]);
  return (
    <Modal
      title={title}
      open={show}
      onOk={() => onOk({ ...formValue, ...form.getFieldsValue() })}
      onCancel={onCancel}
    >
      <Form
        initialValues={formValue}
        form={form}
        labelCol={{ span: 4 }}
        wrapperCol={{ span: 18 }}
        layout="horizontal"
      >
        <Form.Item<any> label="标题" name="title" required>
          <Input />
        </Form.Item>
        <Form.Item<any> label="内容" name="detail" required>
          <Editor />
        </Form.Item>
      </Form>
    </Modal>
  );
}
